/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package consumo.face.cadastro.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

/**
 *
 * @author Carlos Taschetto
 */
@FacesConverter(value="cepConverter")  
public class CEPConverter implements Converter {
    
    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) throws ConverterException {
        /*
        * Irá converter CEP formatado para um sem  traço.
        * Ex.: 35598-870 torna-se 35598870.
        */
        System.out.println("caiu aqui");
        Integer result = null;
        String cep = value;
        try{
            if (value!= null && !value.equals("")){
                cep = value.replaceAll("\\-", "");
                result = Integer.parseInt(cep);
            }
        }catch(NumberFormatException e){
            throw new ConverterException(e);
        }
        return result;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) throws ConverterException {
            System.out.println("Valor:"+value);
            String cep= value.toString();
            if (cep != null && cep.length() == 8)
	               cep = cep.substring(0, 5) + "-" + cep.substring(5);
             
        return cep;
    }
    
}
